package com.turnengine.client.local.unit.command;

import com.javabi.command.IExecutableCommand;
import com.javabi.command.IExecutableCommandResponse;
import com.javabi.command.serializer.AbstractCommandDataSerializer;
import com.javabi.common.io.data.IDataReader;
import com.javabi.common.io.data.IDataWriter;
import com.turnengine.client.local.unit.bean.IUnit;
import com.turnengine.client.local.unit.bean.UnitSerializer;
import com.turnengine.client.local.unit.enums.UnitMove;
import com.turnengine.client.local.unit.enums.UnitNode;
import com.turnengine.client.local.unit.enums.UnitType;
import java.io.IOException;

/**
 * The Add Unit Data Serializer.
 */
public class AddUnitDataSerializer extends AbstractCommandDataSerializer<IUnit> implements IAddUnitDataSerializer {

	/**
	 * Creates a new Add Unit Data Serializer.
	 */
	public AddUnitDataSerializer() {
		super(AddUnit.COMMAND_ID);
	}

	@Override
	public IUnit readReturnValue(IDataReader reader) throws IOException {
		IUnit value = new UnitSerializer().readObject(reader);
		return value;
	}

	@Override
	public void writeReturnValue(IDataWriter writer, IUnit value) throws IOException {
		new UnitSerializer().writeObject(writer, value);
	}

	@Override
	public IExecutableCommand<IUnit> readRequest(IDataReader reader) throws IOException {

		// Read fields
		long loginId = reader.readLong();
		int instanceId = reader.readInt();
		String name = reader.readString(true);
		UnitNode node = reader.readEnum(UnitNode.class, true);
		UnitType type = reader.readEnum(UnitType.class, true);
		UnitMove move = reader.readEnum(UnitMove.class, true);
		String groupName = reader.readString(true);
		String factionName = reader.readString(true);

		// Create object
		AddUnit object = new AddUnit();
		object.setLoginId(loginId);
		object.setInstanceId(instanceId);
		object.setName(name);
		object.setNode(node);
		object.setType(type);
		object.setMove(move);
		object.setGroupName(groupName);
		object.setFactionName(factionName);
		return object;
	}

	@Override
	public void writeRequest(IDataWriter writer, IExecutableCommand<IUnit> argument) throws IOException {
		AddUnit object = (AddUnit) argument;

		// Get fields
		long loginId = object.getLoginId();
		int instanceId = object.getInstanceId();
		String name = object.getName();
		UnitNode node = object.getNode();
		UnitType type = object.getType();
		UnitMove move = object.getMove();
		String groupName = object.getGroupName();
		String factionName = object.getFactionName();

		// Write fields
		writer.writeLong(loginId);
		writer.writeInt(instanceId);
		writer.writeString(name, true);
		writer.writeEnum(node, true);
		writer.writeEnum(type, true);
		writer.writeEnum(move, true);
		writer.writeString(groupName, true);
		writer.writeString(factionName, true);
	}

	@Override
	public IExecutableCommandResponse<IUnit> newResponse() {
		return new AddUnitResponse();
	}
}
